/* enum */
import { FieldTypeMappingEnum, LogisticsFieldNameMappingEnum } from '@model/enum/FieldMappingEnum'
/* entity */
import Field from '@model/entity/Field'
/* service */
import { isLogisticsField } from '@service/FieldService'
/* util */
import { randomString } from 'pub-bbx-utils'
import _ from 'lodash'
import { isEmpty } from '@src/util/type'
import i18n from '@src/locales';

// 物流公司字段
function getLogisticsCompanyField(LogisticsField: Field): Field {
  let { fieldName, isNull, setting } = LogisticsField;
  return {
    ...LogisticsField,
    // displayName: '物流公司',
    displayName: i18n.t('common.base.logisticsCompany') as string,
    field: `${fieldName}_${LogisticsFieldNameMappingEnum.LogisticsCompany}`,
    fieldName: `${fieldName}_${LogisticsFieldNameMappingEnum.LogisticsCompany}`,
    formType: FieldTypeMappingEnum.Logistics,
    id: randomString(),
    isSystem: LogisticsField.isSystem,
    isSearch: LogisticsField.isSearch,
    setting,
    isNull,
    tableName: LogisticsField.tableName
  };
}

// 物流单号字段
function getLogisticsNoField(LogisticsField: Field): Field {
  let { fieldName, isNull, setting } = LogisticsField;
  return {
    ...LogisticsField,
    // displayName: '物流单号',
    displayName: i18n.t('common.base.logisticsNo') as string,
    field: `${fieldName}_${LogisticsFieldNameMappingEnum.LogisticsNo}`,
    fieldName: `${fieldName}_${LogisticsFieldNameMappingEnum.LogisticsNo}`,
    formType: FieldTypeMappingEnum.Logistics,
    id: randomString(),
    isSystem: LogisticsField.isSystem,
    isSearch: LogisticsField.isSearch,
    setting,
    isNull,
    tableName: LogisticsField.tableName
  };
}

/**
 * @description 物流字段展开为物流公司、物流单号
 * @return {Field[]} 展开的字段列表
 */
function smoothLogisticsField(fields: Field[]): Field[] {
  
  const originFields: Field[] = _.cloneDeep(fields)
  
  // 物流字段索引列表
  const logisticsFieldIndexList: number[] = []
  
  originFields.forEach((originField, index) => {
    
    if (isLogisticsField(originField)) {
      logisticsFieldIndexList.push(index)
    }
    
  })
  
  if (isEmpty(logisticsFieldIndexList)) {
    return originFields
  }
  
  let logisticsIndex = 0
  
  logisticsFieldIndexList.forEach((logisticsFieldIndex, index) => {
    
    logisticsIndex = logisticsIndex == 0 ? logisticsFieldIndex : logisticsFieldIndex + index
    
    // 物流字段
    const logisticsField: Field = fields[logisticsFieldIndex]
    
    // 物流字段列表
    const logisticsAllFields = [
      getLogisticsCompanyField(logisticsField),
      getLogisticsNoField(logisticsField)
    ]
    
    // 替换物流字段为物流公司、物流单号
    originFields.splice(logisticsIndex, 1, ...logisticsAllFields)
    
  })
  
  return originFields.filter(field => Boolean(field))
}

export { 
  getLogisticsCompanyField, 
  getLogisticsNoField,
  smoothLogisticsField
};

export default {
  smoothLogisticsField
};
